﻿using App_Code.Helpers;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using PluginDB;

namespace App_Code.SiteParsers
{
    /// <summary>
    /// Summary description for TheTVDBScraper
    /// </summary>
    public class TheTVDBScraper
    {
        const string BASE_URL = "http://thetvdb.com";
        const string SEARCH_URL = "http://thetvdb.com/?string={0}&searchseriesid=&tab=listseries&function=Search";

        public static TVDBInformationItem GetTVDBInformation(string searchName)
        {
            string url = string.Format(SEARCH_URL, searchName);
            string page = Utils.GetPage(url, Encoding.UTF8);
            var tvdbInformationItem = new TVDBInformationItem {Name = searchName};

            const string resultTableExpression = "<tr><td class=\".*?\"><a href=\"(.+?)\">(.*?)</a>.*?</td><td class=\".*?\">(.*?)</td><td class=\".*?\">.*?</td></tr>";
            var matches = Regex.Matches(page, resultTableExpression, RegexOptions.Singleline);

            var hebrewUrl = string.Empty;
            var englishUrl = string.Empty;
            
            foreach (Match match in matches)
            {
                var pageLink = match.Groups[1].Value;
                var language = match.Groups[3].Value;
                var name = match.Groups[2].Value;
                if (language.Trim().ToLower().Equals("עברית") &&
                    name.Trim().ToLower().Equals(searchName))
                {
                    hebrewUrl = BASE_URL + pageLink;
                }
                else if (   language.Trim().ToLower().Equals("english") &&
                            name.Trim().ToLower().Equals(searchName))
                {
                    englishUrl = BASE_URL + pageLink;
                }

                if (!string.IsNullOrEmpty(hebrewUrl) &&
                    !string.IsNullOrEmpty(englishUrl))
                {
                    break;
                }
            }

            if (!string.IsNullOrEmpty(hebrewUrl))
            {
                ExtractItemPage(tvdbInformationItem, hebrewUrl);
            }
            else if (!string.IsNullOrEmpty(englishUrl))
            {
                ExtractItemPage(tvdbInformationItem, englishUrl);
            }
            else
            {
                tvdbInformationItem.IsValid = false;
                Debug.WriteLine(string.Format("Cant find {0} in TheTVDB", searchName));
            }

            return tvdbInformationItem;
        }

        private static void ExtractItemPage(TVDBInformationItem tvdbInformationItem, string url)
        {
            url = url.Replace("&amp;", "&");
            var page = Utils.GetPage(Utils.LoopDecodeUrl(url), Encoding.UTF8);

            #region plot
            var plotExpression = string.Format("<h1>{0}</h1>(.+?)</td>", tvdbInformationItem.Name);
            var plotMatch = Regex.Match(page, plotExpression, RegexOptions.Singleline);
            if (plotMatch.Success)
            {

                tvdbInformationItem.Plot = Utils.CleanHtmlContent(Regex.Match(plotMatch.Value, "</h1>(.+?)</div>", RegexOptions.Singleline).Groups[1].Value);
            }
            #endregion

            #region FanArt
            const string fanartExpression = "<h1>Fan Art</h1>.*?<table(.+?)</table>";
            var fanartMatch = Regex.Match(page, fanartExpression, RegexOptions.Singleline);
            if (!fanartMatch.Success) return;

            const string resultExpression = "<a href=\"banners(.*?)\" target=\"_blank\">(.*?)</a>";
            var matches = Regex.Matches(fanartMatch.Value, resultExpression, RegexOptions.Singleline);
            foreach (Match match in matches)
            {
                var fanartLink = match.Groups[1].Value;
                var name = match.Groups[2].Value;
                if (!name.ToLower().Equals("view full size")) continue;

                tvdbInformationItem.FanartUrl = string.Format("{0}/banners{1}", BASE_URL, fanartLink);
                break;
            }
            #endregion

            #region Genre
            const string genreExpression = "<td align=\"right\" id=\"labels\">Genre:</td>.*?<td align=\"right\">(.+?)</td>";
            var genreMatch = Regex.Match(page, genreExpression, RegexOptions.Singleline);
            if (genreMatch.Success)
            {
                tvdbInformationItem.Genre = genreMatch.Groups[1].Value; //TODO: ADD genre to DB
            }
            #endregion
        }
    }
}